import _ from 'underscore'
import $ from 'jquery'
import moment from 'moment'
import {Scope} from 'lib/scopeFactory'

import {coreApi,sortMap,parseToChart,parseToTopbar} from '../apis/core-util'

var currentTimestamp = moment(BlueWare.timestamp).startOf('day')
var hourAgoStart = BlueWare.timestamp - 60*60*1000
  , hourAgoEnd = BlueWare.timestamp
  , todayStartTime = currentTimestamp.valueOf()
  , todayEndTime = moment(todayStartTime).add(1,'days').valueOf() - 1
  , yesterdayStartTime = moment(todayStartTime).subtract(1, 'days').valueOf()
  , yesterdayEndTime = yesterdayStartTime + 24*60*60*1000 - 1
  , sevenAgoStartTime = moment(todayStartTime).subtract(6, 'days').valueOf()
  , sevenAgoEndTime = sevenAgoStartTime + 24*60*60*1000 - 1
  , thirtyDayStartTime = moment(todayStartTime).subtract(30, 'days').valueOf()
  , thirtyDayEndTime = thirtyDayStartTime + 24*60*60*1000 - 1
  , fifteenDayStartTime = moment(todayStartTime).subtract(14, 'days').valueOf()
  , fifteenDayEndTime = fifteenDayStartTime + 24*60*60*1000 - 1

var dayActiveTime = {
  'day':{
    urlName:'activeSessionSeries',
    startTime:todayEndTime - 12*24*60*60*1000,
    endTime:todayEndTime,
    size:12
  },
  'week':{
    urlName:'activeSessionSeriesNew',
    queryType:'101',
    size:12
  },
  'month':{
    urlName:'activeSessionSeriesNew',
    queryType:'102',
    size:12
  }
}

export default class MainScope extends Scope {
  constructor(){
    super();
    this._cache = {}
    this.$state = {
      totalNum:0,
      dayState:'day',
      currentTab:1,
      chart_day_compare:{
        loading:true
      },
      chart_range:{
        loading:true
      },
      chart_pre_geo:{
        loading:true
      },
      chart_pre_version:{
        loading:true
      },
      chart_pre_os:{
        loading:true
      }
    }
    this.tabApis = {
      'day_compare':{
        isFetched:false,
        api:[{
          name:'今天',
          timeStrict:0,
          api:coreApi({
            urlName:'activeSessionSeries',
            viewKey:'active',
            order:'1',
            limit:5,
            startTime:todayStartTime,
            endTime:todayEndTime
          })
        },{
          name:'昨天',
          timeStrict:24*60*60*1000,
          api:coreApi({
            urlName:'activeSessionSeries',
            viewKey:'active',
            order:'1',
            limit:5,
            startTime:yesterdayStartTime,
            endTime:yesterdayEndTime
          })
        },{
          name:'7天',
          timeStrict:6*24*60*60*1000,
          api:coreApi({
            urlName:'activeSessionSeries',
            viewKey:'active',
            order:'1',
            limit:5,
            startTime:sevenAgoStartTime,
            endTime:sevenAgoEndTime
          })
        },{
          name:'15天',
          timeStrict:14*24*60*60*1000,
          api:coreApi({
            urlName:'activeSessionSeries',
            viewKey:'active',
            order:'1',
            limit:5,
            startTime:fifteenDayStartTime,
            endTime:fifteenDayEndTime
          })
        }]
      },
      'pre_geo':{
        isFetched:false,
        api:coreApi({
          urlName:'activeSessionSeries',
          viewKey:'active',
          order:'1',
          size:15,
          limit:5,
          startTime:fifteenDayStartTime,
          endTime:todayEndTime,
          classify:'region'
        })
      },
      'pre_version':{
        isFetched:false,
        api:coreApi({
          urlName:'activeSessionSeries',
          viewKey:'active',
          order:'1',
          size:15,
          limit:5,
          startTime:fifteenDayStartTime,
          endTime:todayEndTime,
          classify:'appversion'
        })
      },
      'pre_os':{
        isFetched:false,
        api:coreApi({
          urlName:'activeSessionSeries',
          viewKey:'active',
          order:'1',
          size:15,
          limit:5,
          startTime:fifteenDayStartTime,
          endTime:todayEndTime,
          classify:'osversion'
        })
      }
    }
    this.pre_dayApi = coreApi({
      viewKey:'active',
      order:'1'
    },() => dayActiveTime[this.$state.dayState])

  }
  fetch(){
    if(this._cache[this.$state.dayState]){
      this.$state['chart_range'] = {
        data:this._cache[this.$state.dayState]
      }
      this.emit()
    }else{
      this.pre_dayApi.fetch().then((data,params) => {
        data.result[0].data = _.sortBy(data.result[0].data, 'st');
        if(this.$state.dayState==='day'){
          if(data.result.length&&data.result[0]['data'].length){
            this.$state.totalNum = _(data.result[0]['data']).last().val
          }
        }
        this.$state['chart_range'] = {
          data:parseToChart(data,params)
        }
        this._cache[this.$state.dayState] = this.$state['chart_range'].data
      },(data,params) => {
        this.$state['chart_range'] = {
          error:err
        }
      },(data,params) => {
        this.$state['chart_range'] = {
          loading:true,
          params:params
        }
        this.emit()
      }).always(() => {
        this.emit()
      })
    }
  }
  $pre_size(payload){
    this.$state.dayState = payload.key
    this.fetch()
  }
  $switch_tab(payload){
    var _this = this
    var key = payload.key
    var index = payload.index
    var tabApi = this.tabApis[key]
    this.$state.currentTab = index
    if(!tabApi.isFetched){
      if(_.isArray(tabApi.api)){
        $.when.apply($,_.map(tabApi.api,function(p){
          return p.api.fetch()
        })).then(function(){
          var args = [].slice.call(arguments)
          var params = args[0][1]
          var results = _(args).map(function(i,n){
            return parseToChart(i[0],params)
          })
          var data = {
            series:_.chain(tabApi.api).map(function(serie,n){
              var orgData = results[n].series.length?results[n]['series'][0]['data']:[]
              return _.extend({},_(serie).pick('name'),{
                data:_.chain(orgData).map(function(point){
                  return _.extend({},point,{
                    x:point['x']+serie.timeStrict
                  })
                },_this).value()
              });
            },_this).value(),
            yAxis:results[0].yAxis
          }
          _this.$state.chart_day_compare = {
            data:data
          }
        },(err) => {
          this.$state.chart_day_compare = {
            error:err
          }
        },(params) => {
          this.$state.chart_day_compare = {
            loading:true,
            params:params
          }
          this.emit()
        }).always(() => {
          this.emit()
        })
      }else{
        tabApi.api.fetch().then((data,params) => {
          this.$state['chart_'+key] = {
            data:parseToChart(data,params)
          }
        },(data,params) => {
          this.$state['chart_'+key] = {
            error:err
          }
        },(data,params) => {
          this.$state['chart_'+key] = {
            loading:true,
            params:params
          }
          this.emit()
        }).always(() => {
          this.emit()
        })
      }

      tabApi.isFetched = true
    }else{
      this.emit()
    }
  }
  $load(){
    this.fetch()
    this.$switch_tab({
      key:'day_compare',
      index:1
    })
  }
}
